from utils.page import Page, PageResult
from tortoise.models import Model, QuerySet, MODEL
from models.base import BaseModel


class BaseService:
    user_id = None
    tenant_id = None
    page = Page()

    @classmethod
    def activate_session(cls, session):
        if session:
            cls.user_id = session.user_id
            cls.tenant_id = session.tenant_id
        else:
            cls.user_id = None
            cls.tenant_id = None

    @classmethod
    async def page_list(cls, current: QuerySet[MODEL], *val) -> PageResult:
        total = await current.count()
        pg = cls.page

        pn = pg.page_num
        pages = total // pg.page_size if total % pg.page_size == 0 else total // pg.page_size + 1
        offset_num = (pn - 1) * pg.page_size

        page_dict = {"current_page_num": pn, "page_size": pg.page_size, "total_num": total, "pages": pages}
        dt = await current.offset(offset_num).limit(pg.page_size)
        page_dict.update(data=[await item.list_to_dict() for item in dt])

        return PageResult(**page_dict)
